<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue'
import { useIcon } from '@/hooks/web/useIcon'
import { Dialog } from '@/components/Dialog'
import {
  ElCard,
  ElButton,
  ElSelect,
  ElOption,
  ElTable,
  ElTableColumn,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElCheckbox,
  ElMessage
} from 'element-plus'
import { RetrieveVariety } from '@/api/sysmanage/variety'
import { RetrieveIndex } from '@/api/syscontent/datlib'
import {
  RetrieveFormulaGroup,
  CreateFormulaGroup,
  UpdateFormulaGroup,
  RetrieveFormula,
  CreateFormula,
  UpdateFormula,
  RetrieveColumn,
  CreateColumn,
  UpdateColumn
} from '@/api/syscontent/vformula'
import { FormulaGroup, GroupItem, FormulaItem, columnItem } from './types/formula'
const plusIcon = useIcon({ icon: 'system-uicons:plus' })
const varietyList = ref<Array<{ code: string; name: string }>>([])
const indexForSelect = ref<Array<{ id: number; name: string; plat: string }>>([])
const groupData = reactive<{ varietyEn: string; groups: Array<GroupItem> }>({
  varietyEn: '',
  groups: []
})
const groupDiag = reactive({
  isShow: false,
  showTitle: '编辑分组',
  confirmButtonText: '确定新建',
  confirmLoading: false
})
const initGroupItem: FormulaGroup = {
  id: -1,
  name: '',
  sort_num: 1,
  parent_id: 0,
  vcode: '',
  is_active: false
}
const editGroupItem = reactive<FormulaGroup>(JSON.parse(JSON.stringify(initGroupItem)))

const formulaData = reactive<{ group_id: string; formulaList: Array<FormulaItem> }>({
  group_id: '',
  formulaList: []
})
const formulaDiag = reactive({
  isShow: false,
  showTitle: '新建公式',
  confirmButtonText: '确定新建',
  confirmLoading: false
})
const initFormulaItem: FormulaItem = {
  id: -1,
  rid: -1,
  name: '',
  unit: '',
  formula: '',
  fma_explain: '',
  sort_num: 1,
  is_active: false
}
const editFormulaItem = reactive<FormulaItem>(JSON.parse(JSON.stringify(initFormulaItem)))

const columnDiag = reactive({
  isShow: false,
  showTitle: '新建公式列',
  confirmButtonText: '确定新建',
  confirmLoading: false
})
const columnData = reactive<{ formula_id: string; columnList: Array<columnItem> }>({
  formula_id: '',
  columnList: []
})
const initColumItem: columnItem = {
  id: -1,
  name: '',
  unit: '',
  is_constant: false,
  constant: null,
  is_index: false,
  sort_num: 1,
  is_show: false
}
const editColumnItem = reactive<columnItem>(JSON.parse(JSON.stringify(initColumItem)))

const varietySelectChange = (v: string) => {
  groupData.varietyEn = v
  editGroupItem.vcode = v
  loadFormulaGroupList()
}
const toCreateNewGroup = () => {
  groupDiag.showTitle = '新建分组'
  groupDiag.confirmButtonText = '确定新建'
  Object.assign(editGroupItem, initGroupItem)
  editGroupItem.id = -1
  editGroupItem.gid = -1
  editGroupItem.vcode = groupData.varietyEn
  editGroupItem.parent_id = 0
  groupDiag.isShow = true
}
const toShowEditGroupDiag = (row: FormulaGroup) => {
  Object.assign(editGroupItem, row)
  groupDiag.showTitle = '编辑分组'
  groupDiag.confirmButtonText = '确定保存'
  editGroupItem.gid = row.id
  groupDiag.isShow = true
}
const toConfirmSaveGroup = async () => {
  let retData: any = null
  groupDiag.confirmLoading = true
  if (editGroupItem.gid && editGroupItem.gid < 0) {
    retData = await CreateFormulaGroup(editGroupItem)
  } else {
    retData = await UpdateFormulaGroup(editGroupItem)
  }
  groupDiag.confirmLoading = false
  groupDiag.isShow = false
  ElMessage.success(retData.message)
  loadFormulaGroupList()
}

const groupSelectChange = (group: string) => {
  formulaData.group_id = group
  loadFormulaList()
}
const toCreateNewFormula = () => {
  formulaDiag.showTitle = '新建公式'
  formulaDiag.confirmButtonText = '确定新建'
  Object.assign(editFormulaItem, initFormulaItem)
  editFormulaItem.id = -1
  editFormulaItem.rid = -1
  editFormulaItem.gid = parseInt(formulaData.group_id)
  editFormulaItem.vcode = groupData.varietyEn
  formulaDiag.isShow = true
}
const toShowEditFormula = (row: FormulaItem) => {
  Object.assign(editFormulaItem, row)
  editFormulaItem.id = row.id
  editFormulaItem.rid = row.id
  formulaDiag.showTitle = '编辑公式'
  formulaDiag.confirmButtonText = '确定保存'
  formulaDiag.isShow = true
}
const toConfirmSaveFormula = async () => {
  let retData: any = null
  if (editFormulaItem.id && editFormulaItem.id < 0) {
    retData = await CreateFormula(editFormulaItem)
  } else {
    retData = await UpdateFormula(editFormulaItem)
  }
  ElMessage.success(retData.message)
  formulaDiag.isShow = false
  loadFormulaList()
}

const formulaSelectChange = (fid: string) => {
  columnData.formula_id = fid
  editColumnItem.formula_id = parseInt(fid)
  loadColumnList()
}
const toCreateNewColumn = () => {
  Object.assign(editColumnItem, initColumItem)
  editColumnItem.id = -1
  columnDiag.showTitle = '新建数据列'
  columnDiag.confirmButtonText = '确定新建'
  columnDiag.isShow = true
}
const toShowEditColumn = (row: columnItem) => {
  Object.assign(editColumnItem, row)
  columnDiag.showTitle = '编辑公式列'
  columnDiag.confirmButtonText = '确定保存'
  editColumnItem.rid = row.id
  columnDiag.isShow = true
}
const toConfirmSaveColumn = async () => {
  let retData: any = null
  if (editColumnItem.id && editColumnItem.id < 0) {
    retData = await CreateColumn(editColumnItem)
  } else {
    retData = await UpdateColumn(editColumnItem)
  }
  ElMessage.success(retData.message)
  columnDiag.isShow = false
  loadColumnList()
}

const loadFormulaGroupList = () => {
  groupData.groups = []
  if (!groupData.varietyEn) return
  RetrieveFormulaGroup({ vcode: groupData.varietyEn }).then((res) => {
    groupData.groups = res.data.data
  })
}
const loadFormulaList = () => {
  formulaData.formulaList = []
  if (!formulaData.group_id) return
  RetrieveFormula({ gid: parseInt(formulaData.group_id) }).then((res) => {
    // console.log(res)
    formulaData.formulaList = res.data.data
  })
}
const loadColumnList = () => {
  columnData.columnList = []
  if (!columnData.formula_id) return
  RetrieveColumn({ fid: parseInt(columnData.formula_id) }).then((res) => {
    columnData.columnList = res.data.data
  })
}

const remoteQueryIndex = (kw: string) => {
  RetrieveIndex({ kw, page: 1, page_size: 100 }).then((res) => {
    indexForSelect.value = res.data.data.rows
    console.log(res)
  })
}

onMounted(() => {
  RetrieveVariety({ kw: '', scope: 'S06', code: '' }).then((res) => {
    varietyList.value = res.data.data
  })
})
</script>
<template>
  <div class="page-view">
    <ElCard shadow="hover">
      <template #header>
        <div class="card-header">
          <Icon icon="uil:setting" />
          <div class="name">1、公式分组</div>
        </div>
      </template>
      <div class="actions">
        <ElSelect
          v-model="groupData.varietyEn"
          placeholder="选择品种"
          @change="varietySelectChange"
        >
          <ElOption v-for="v in varietyList" :key="v.code" :value="v.code" :label="v.name" />
        </ElSelect>
        <div class="right-action">
          <ElButton
            type="primary"
            :icon="plusIcon"
            :disabled="!groupData.varietyEn"
            @click="toCreateNewGroup"
          >
            新建
          </ElButton>
        </div>
      </div>
      <ElTable
        border
        stripe
        style="margin-top: 10px"
        empty-text="该品种暂无公式分组"
        :data="groupData.groups"
      >
        <ElTableColumn prop="id" label="ID" width="80">
          <template #default="scope">
            <div class="edit-column" @click="toShowEditGroupDiag(scope.row)">
              <Icon class="edit-icon" icon="svg-icon:box-edit" />
              <div class="row-id">{{ scope.row.id }}</div>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn prop="name" label="名称" />
        <ElTableColumn prop="sort_num" label="排序" width="70" />
        <ElTableColumn label="有效" width="70" align="center">
          <template #default="scope">
            <Icon v-if="scope.row.is_active" icon="svg-icon:dash-yes" />
          </template>
        </ElTableColumn>
      </ElTable>
    </ElCard>
    <div class="gap"></div>
    <ElCard shadow="hover">
      <template #header>
        <div class="card-header">
          <Icon icon="uil:setting" />
          <div class="name">2、组内公式</div>
        </div>
      </template>
      <div class="actions">
        <ElSelect
          v-model="formulaData.group_id"
          placeholder="请选择组别"
          @change="groupSelectChange"
        >
          <ElOption v-for="g in groupData.groups" :key="g.id" :value="g.id" :label="g.name" />
        </ElSelect>
        <div class="right-action">
          <ElButton
            type="primary"
            :icon="plusIcon"
            :disabled="formulaData.group_id ? parseInt(formulaData.group_id) < 0 : true"
            @click="toCreateNewFormula"
          >
            新建
          </ElButton>
        </div>
      </div>
      <ElTable
        border
        stripe
        style="margin-top: 10px"
        empty-text="该组下还没有配置公式"
        :data="formulaData.formulaList"
      >
        <ElTableColumn prop="id" label="ID" width="80">
          <template #default="scope">
            <div class="edit-column" @click="toShowEditFormula(scope.row)">
              <Icon class="edit-icon" icon="svg-icon:box-edit" />
              <div class="row-id">{{ scope.row.id }}</div>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn prop="name" label="名称" width="200" show-overflow-tooltip />
        <ElTableColumn prop="formula" label="公式" width="400" show-overflow-tooltip />
        <ElTableColumn prop="fma_explain" label="说明" show-overflow-tooltip />
        <ElTableColumn prop="unit" label="单位" width="90" />
        <ElTableColumn prop="sort_num" label="排序" width="70" />
        <ElTableColumn label="有效" width="70" align="center">
          <template #default="scope">
            <Icon v-if="scope.row.is_active" icon="svg-icon:dash-yes" />
          </template>
        </ElTableColumn>
      </ElTable>
    </ElCard>
    <div class="gap"></div>
    <ElCard shadow="hover">
      <template #header>
        <div class="card-header">
          <Icon icon="uil:setting" />
          <div class="name">3、公式候选列</div>
        </div>
      </template>
      <div class="actions">
        <ElSelect
          v-model="columnData.formula_id"
          placeholder="请选择公式"
          @change="formulaSelectChange"
        >
          <ElOption
            v-for="f in formulaData.formulaList"
            :key="f.id"
            :value="f.id"
            :label="f.name"
          />
        </ElSelect>
        <div class="right-action">
          <ElButton
            type="primary"
            :icon="plusIcon"
            :disabled="columnData.formula_id ? parseInt(columnData.formula_id) < 0 : true"
            @click="toCreateNewColumn"
          >
            新建
          </ElButton>
        </div>
      </div>
      <ElTable border stripe style="margin-top: 10px" :data="columnData.columnList">
        <ElTableColumn prop="id" label="ID" width="80">
          <template #default="scope">
            <div class="edit-column" @click="toShowEditColumn(scope.row)">
              <Icon class="edit-icon" icon="svg-icon:box-edit" />
              <div class="row-id">{{ scope.row.id }}</div>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn prop="name" label="名称" />
        <ElTableColumn prop="unit" label="单位" width="100" />
        <ElTableColumn label="常数" width="70" align="center">
          <template #default="scope">
            <Icon v-if="scope.row.is_constant" icon="svg-icon:dash-yes" />
          </template>
        </ElTableColumn>
        <ElTableColumn prop="constant" label="值" width="100" />
        <ElTableColumn label="指标" width="70" align="center">
          <template #default="scope">
            <Icon v-if="scope.row.is_index" icon="svg-icon:dash-yes" />
          </template>
        </ElTableColumn>
        <ElTableColumn prop="index_id" label="指标ID" width="120" />
        <ElTableColumn prop="sort_num" label="排序" width="100" />
        <ElTableColumn label="显示" width="70" align="center">
          <template #default="scope">
            <Icon v-if="scope.row.is_show" icon="svg-icon:dash-yes" />
          </template>
        </ElTableColumn>
      </ElTable>
    </ElCard>
    <Dialog v-model="groupDiag.isShow" :title="groupDiag.showTitle">
      <ElForm>
        <ElFormItem label="名称">
          <ElInput v-model="editGroupItem.name" placeholder="输入公式组别名称" />
        </ElFormItem>
        <ElFormItem label="排序">
          <ElInputNumber v-model="editGroupItem.sort_num" :min="1" />
        </ElFormItem>
        <ElFormItem label="有效">
          <ElCheckbox v-model="editGroupItem.is_active" />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="groupDiag.isShow = false">取消</ElButton>
        <ElButton type="primary" :loading="groupDiag.confirmLoading" @click="toConfirmSaveGroup">
          {{ groupDiag.confirmButtonText }}
        </ElButton>
      </template>
    </Dialog>
    <Dialog v-model="formulaDiag.isShow" :title="formulaDiag.showTitle">
      <ElForm>
        <ElFormItem label="公式名称">
          <ElInput v-model="editFormulaItem.name" placeholder="输入公式的名称" />
        </ElFormItem>
        <ElFormItem label="公式描述">
          <ElInput
            v-model="editFormulaItem.formula"
            placeholder="新建时可留空，配置好计算列再填写"
          />
        </ElFormItem>
        <ElFormItem label="结果单位">
          <ElInput v-model="editFormulaItem.unit" placeholder="计算结果单位" />
        </ElFormItem>
        <ElFormItem label="文字公式">
          <ElInput v-model="editFormulaItem.fma_explain" placeholder="公式的文字说明" />
        </ElFormItem>
        <ElFormItem label="排序">
          <ElInputNumber v-model="editFormulaItem.sort_num" />
        </ElFormItem>
        <ElFormItem label="有效">
          <ElCheckbox v-model="editFormulaItem.is_active" />
        </ElFormItem>
      </ElForm>
      <ElTable border stripe size="small" :data="columnData.columnList">
        <ElTableColumn prop="id" label="ID" width="100" />
        <ElTableColumn prop="name" label="名称" />
      </ElTable>
      <template #footer>
        <ElButton @click="formulaDiag.isShow = false">取消</ElButton>
        <ElButton
          type="primary"
          :loading="formulaDiag.confirmLoading"
          @click="toConfirmSaveFormula"
        >
          {{ formulaDiag.confirmButtonText }}
        </ElButton>
      </template>
    </Dialog>
    <Dialog v-model="columnDiag.isShow" :title="columnDiag.showTitle">
      <ElForm label-position="right" label-width="70">
        <ElFormItem label="名称">
          <ElInput v-model="editColumnItem.name" placeholder="输入列的名称" />
        </ElFormItem>
        <ElFormItem label="单位">
          <ElInput v-model="editColumnItem.unit" placeholder="输入单位" />
        </ElFormItem>
        <ElFormItem label="是否常数">
          <div class="diag-flex-col">
            <ElCheckbox v-model="editColumnItem.is_constant" />
            <ElInput
              style="margin-left: 10px"
              v-model="editColumnItem.constant"
              placeholder="为常数时必填"
            />
          </div>
        </ElFormItem>
        <ElFormItem label="是否指标">
          <div class="diag-flex-col">
            <ElCheckbox v-model="editColumnItem.is_index" />
            <ElSelect
              v-model="editColumnItem.index_id"
              filterable
              remote
              placeholder="关键字搜索指标"
              style="margin-left: 10px; width: 100%"
              :remote-method="remoteQueryIndex"
            >
              <ElOption
                v-for="item in indexForSelect"
                :key="item.id"
                :value="item.id"
                :label="`${item.name} (${item.plat})`"
              />
            </ElSelect>
          </div>
        </ElFormItem>
        <ElFormItem label="排序">
          <ElInputNumber v-model="editColumnItem.sort_num" :min="1" />
        </ElFormItem>
        <ElFormItem label="显示">
          <ElCheckbox v-model="editColumnItem.is_show">是</ElCheckbox>
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="columnDiag.isShow = false">取消</ElButton>
        <ElButton type="primary" :loading="columnDiag.confirmLoading" @click="toConfirmSaveColumn">
          {{ columnDiag.confirmButtonText }}
        </ElButton>
      </template>
    </Dialog>
  </div>
</template>
<style scoped lang="less">
.page-view {
  .gap {
    height: 10px;
  }
  .card-header {
    display: flex;
    align-items: center;

    .name {
      color: #f86e00;
      font-weight: 700;
      margin-left: 5px;
    }
  }
  .edit-column {
    display: flex;
    align-items: center;
    cursor: pointer;
    .edit-icon {
      margin-right: 5px;
    }
  }
  .actions {
    display: flex;
    align-items: center;
    .right-action {
      margin-left: auto;
    }
  }
  .diag-flex-col {
    display: flex;
    align-items: center;
    flex: 1;
  }
}
</style>
